package com.monster.mechanic.dbmodel.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

/**
 * The class works to load the configurations to connect the database trought
 * hibernate
 * 
 * @author ISAY ARENAS SOTO
 * @email isay.arenas@monster.com.mx
 * 
 */
public class HibernateUtil {
	/** The single instance of hibernate SessionFactory */
	private static SessionFactory sessionFactory;

	private HibernateUtil() {
	}

	static {
		try {
			HbmConfigAnnotations xml = new HbmConfigAnnotations();
			xml.configure();
			Configuration configure = new Configuration().configure(xml
					.getFuenteXml());
			xml.buildMetaData(configure);
			ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
					.applySettings(configure.getProperties())
					.buildServiceRegistry();
			sessionFactory = configure.buildSessionFactory(serviceRegistry);
		} // try
		catch (Exception e) {
			e.printStackTrace();
		} // catch
	}

	public static SessionFactory getInstance() {
		return sessionFactory;
	}

	public static void close() {
		if (sessionFactory != null)
			sessionFactory.close();
		sessionFactory = null;
	}

	public static void closeSession(Session session) {
		if (session != null) {
			session.close();
		}
		session = null;
	}
}
